<template>
  <div class="container">
    <draggable class="img-wrappe" v-model="files" @end="onDragEnd">
      <div v-for="(file, index) in files" :key="index" class="image-container">
        <button v-if="index > 0" @click="moveLeft(index)" class="move-button left"> < </button>
        <img :src="file" alt="Uploaded image" class="uploaded-image" />
        <button v-if="index < files.length - 1" @click="moveRight(index)" class="move-button right"> > </button>
        <button @click="removeImage(index)" class="remove-button">删除</button>
        <BtnSingleImageUpload :is-show-tip='false' v-model="files[index]" :limit="1">
          <div class="concise-item-image-btn">
            <!-- 上传按钮 -->
            <div class="btn">
              <div>换图</div>
            </div>
          </div>
        </BtnSingleImageUpload>
      </div>
      <el-upload
        class="upload-container"
        :action="uploadFileUrl"
        :on-success="handleUploadSuccess"
        :before-upload="handleBeforeUpload"
        :on-error="handleUploadError"
        :show-file-list="false"
        :headers="headers"
        :multiple="true">
        <div class="upload-button">
          <icon class="el-icon-upload2"></icon>
        </div>
      </el-upload>
    </draggable>
    <div class="handleBtn">
      <p class="handleBtnTip">提示：上传的图片为了显示美观宽高比请设置为9:16。</p>
      <el-button type="primary" size="medium" @click="submitForm">保存</el-button>
    </div>
  </div>
</template>

<script>
import draggable from 'vuedraggable'
import BtnSingleImageUpload from "@/components/BtnSingleImageUpload/index.vue";
import {getToken} from "@/utils/auth";
import { addGuide,editGuide,getGuideInfo } from '@/api/triones/appManage'
export default {
  name: "index",
  components: {
    BtnSingleImageUpload,
    draggable
  },
  data() {
    return {
      imageUrl: '',
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/infra/file/upload",
      headers: { Authorization: "Bearer " + getToken() },
      fileType: ["png", "jpg", "jpeg"],
      fileSize: 5,
      files: [],
      id: undefined
    }
  },
  created() {
    this.reset();
    this.detail();
  },
  methods: {
    reset() {
      this.id = undefined;
      this.files = [];
    },
    detail() {
      getGuideInfo().then(response => {
        if (response.data) {
          this.id = response.data.id;
          this.files = JSON.parse(response.data.content);
        }
      })
    },
    // 上传成功回调
    handleUploadSuccess(res, file) {
      console.log({ name: res.data.url, url: res.data.url })
      console.log('文本图片',URL.createObjectURL(file.raw))
      this.files.push(res.data.url)
      this.$modal.closeLoading();
    },
    // 上传前loading加载
    handleBeforeUpload(file) {
      let isImg = false;
      if (this.fileType.length) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        isImg = this.fileType.some(type => {
          if (file.type.indexOf(type) > -1) return true;
          return !!(fileExtension && fileExtension.indexOf(type) > -1);
        });
      } else {
        isImg = file.type.indexOf("image") > -1;
      }

      if (!isImg) {
        this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}图片格式文件!`);
        return false;
      }
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$modal.msgError(`上传图片大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      this.$modal.loading("正在上传图片，请稍候...");
    },
    // 上传失败
    handleUploadError() {
      this.$modal.msgError("上传图片失败，请重试");
      this.$modal.closeLoading();
    },
    onDragEnd(event) {
    },
    removeImage(index) {
      this.files.splice(index, 1)
    },
    moveLeft(index) {
      if (index > 0) {
        const temp = this.files[index]
        this.$set(this.files, index, this.files[index - 1])
        this.$set(this.files, index - 1, temp)
      }
    },
    moveRight(index) {
      if (index < this.files.length - 1) {
        const temp = this.files[index]
        this.$set(this.files, index, this.files[index + 1])
        this.$set(this.files, index + 1, temp)
      }
    },
    submitForm() {
      if (this.files.length === 0) {
        this.$modal.msgError("请上传图片");
        return;
      }
      const body = {
        id: this.id,
        content: JSON.stringify(this.files)
      }
      if (this.id != null) {
        editGuide(body).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.detail();
        });
      } else {
        addGuide(body).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.detail();
        });
      }
    }
  }
}
</script>

<style scoped lang="scss">
.container {
  padding: 20px;
}

.img-wrappe {
  display: flex;
  width: 100%;
  flex-wrap: wrap;
}

.image-container {
  display: inline-block;
  margin-right: 10px;
  position: relative;
  cursor: grab;
}

.image-container:active {
  cursor: grabbing; /* 或者使用 move */
}

.uploaded-image {
  width: 180px;
  height: 320px;
  object-fit: cover;
}

.move-button {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  background-color: rgb(17, 160, 183);
  color: #ffffff;
  border: none;
  padding: 5px;
  cursor: pointer;
  z-index: 10;
}

.move-button.left {
  left: 5px;
}

.move-button.right {
  right: 5px;
}

.remove-button {
  position: absolute;
  top: 5px;
  right: 5px;
  background-color: red;
  color: white;
  border: none;
  padding: 5px;
  cursor: pointer;
}

.upload-container {
  width: 180px;
  height: 320px;
  display: inline-block;
  position: relative;
  cursor: pointer;
}

.upload-button {
  width: 180px;
  height: 320px;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 24px;
  border-radius: 5px;
  cursor: pointer;
}

.concise-item-image-btn {
  position: absolute;
  top: 5px;
  right: 50px;
  display: flex;
  z-index: 1;

  .btn {
    position: relative;
    display: flex;
    align-items: center;
    line-height: 26px;
    color: #fff;
    font-size: 14px;
    text-align: center;
    border-radius: 3px;
    background: rgba(73, 73, 73, .6);
    padding: 0 5px;
    cursor: pointer;
    box-sizing: border-box;

    .icon-upload {
      width: 16px;
      height: 16px;
      background-repeat: no-repeat;
      background-position: 50%;
      background-image: url('~@/assets/images/icon_upload.png');
      background-size: contain;
      margin-right: 6px;
    }
  }
}

.handleBtn {
    padding:20px 50px;
  .handleBtnTip {
    color: #d31010;
  }
}
</style>
